package com.example.taobaou.ui.fragment;


import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaou.R;
import com.example.taobaou.base.BaseFragment;
import com.example.taobaou.model.domain.Categories;
import com.example.taobaou.model.domain.HomePagerContent;
import com.example.taobaou.model.domain.IBsaeInfo;
import com.example.taobaou.presenter.ICategoryPagerPresenter;
import com.example.taobaou.presenter.impl.TicketPresenterImpl;
import com.example.taobaou.ui.Custom.AutoLoopViewPager;
import com.example.taobaou.ui.adapter.HomePagerContentAdapter;
import com.example.taobaou.ui.adapter.LooperPagerAdapter;
import com.example.taobaou.utils.Constants;
import com.example.taobaou.utils.PresenterManager;
import com.example.taobaou.utils.SizeUtils;
import com.example.taobaou.utils.TicketUtil;
import com.example.taobaou.utils.TostUtils;
import com.example.taobaou.view.ICategoryPagerCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.Views.TBNestedSceolView;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallback, HomePagerContentAdapter.OnListItemClickListener, LooperPagerAdapter.OnLoopPagerItemClickListener {


    private ICategoryPagerPresenter categoryPagerPresenter;
    private int materialId;
    private RecyclerView mContentList;
    private HomePagerContentAdapter contentAdapter;
    private AutoLoopViewPager looperPager;
    private LooperPagerAdapter looperPagerAdapter;
    private TextView currentCategoryTitle;
    private LinearLayout lopperPointContainer;
    private TwinklingRefreshLayout refreshLayout;
    private LinearLayout homePagerParent;//用以获得高度的父类布局
    private TBNestedSceolView nestedScrollView;
    private LinearLayout headContainer;
    private TicketPresenterImpl ticketPresenter;

    public static HomePagerFragment newInstance(Categories.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();

        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID, category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        looperPager.stopLoop();
    }

    @Override
    protected int getRootViewResID() {
        return R.layout.fragment_home_pager;
    }

    @Override
    protected void initView(View rootView) {
        //绑定控件
        mContentList = rootView.findViewById(R.id.home_pager_content_list);
        //设置布局
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置item格式
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.bottom = 5;//上5dp
                outRect.top = 5;//下5dp
            }
        });
        //创建适配器
        contentAdapter = new HomePagerContentAdapter();
        //填入适配器
        mContentList.setAdapter(contentAdapter);
        //绑定轮播图
        looperPager = rootView.findViewById(R.id.looper_pager);
        looperPagerAdapter = new LooperPagerAdapter();
        looperPager.setAdapter(looperPagerAdapter);
        //标题
        currentCategoryTitle = rootView.findViewById(R.id.home_pager_title);
        //圆点指示器
        lopperPointContainer = rootView.findViewById(R.id.looper_point_container);
        //设置下拉加载，加载更多正常
        refreshLayout = rootView.findViewById(R.id.refresh);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(true);
        //绑定父类布局
        homePagerParent = rootView.findViewById(R.id.home_pager_parent);
        //绑定滑动控件
        nestedScrollView = rootView.findViewById(R.id.home_pager_nested);
        //绑定需要获得高度的布局
        headContainer = rootView.findViewById(R.id.head_home_pager_container);
    }

    @Override
    protected void initPresenter() {
        categoryPagerPresenter = PresenterManager.getInstance().getCategoryPagerPresenter();
        categoryPagerPresenter.registerViewCallback(this);
    }

    @Override
    protected void loadData() {
        Bundle arguments = getArguments();
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        materialId = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);

//        Log.d(String.valueOf(HomePagerFragment.class), "title--->" + title);
//        Log.d(String.valueOf(HomePagerFragment.class), "materialId--->" + materialId);

        //加载数据
        if (categoryPagerPresenter != null) {
            categoryPagerPresenter.getCotentByCategoruId(materialId);
        }
        //设置标题
        if (currentCategoryTitle != null) {
            currentCategoryTitle.setText(title);
        }
    }

    @Override
    protected void initListener() {
        //设置轮播图点击
        looperPagerAdapter.setOnLoopPagerItemClickListener(this);
        //设置条目点击
        contentAdapter.setOnListItemClickListener(this);

        //轮播图滑动的监听时间，用以改变圆点指示器的状态
        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (looperPagerAdapter.getDataSize() == 0) {
                    return;
                }
                int targetPosition = position % looperPagerAdapter.getDataSize();
                upDataLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //下拉加载的监听
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                //监听下拉动作
                if (categoryPagerPresenter != null) {
                    categoryPagerPresenter.loaderMore(materialId);
                }
            }

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                //监听上拉事件
                if (categoryPagerPresenter != null) {
                    categoryPagerPresenter.onRefreshLoaderMore(materialId);
                }
            }
        });
        //getViewTreeObserver()  view事件观察者
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //获取需要被滑动的高度并设置给 nestedScrollView，高度未滑动完时滑动事件ns自己拿着，
                // 超过高度之后滑动事件交给recycleView
                int headHight = headContainer.getMeasuredHeight();
                nestedScrollView.setHeaderHeight(headHight);
                //当该布局每次被改变时获得view的高度
                int measuredHeight = homePagerParent.getMeasuredHeight();
                //并将该高度给到recycleview的父布局
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
                layoutParams.height = measuredHeight;
                mContentList.setLayoutParams(layoutParams);
                //当父布局高度加载完毕已经被固定的时候，就删除掉观察者，防止因为视图频繁切换导致频繁调用方法，节省资源
                if (measuredHeight != 0) {
                    homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
    }

    //切换指示器
    private void upDataLooperIndicator(int targetPosition) {
        for (int i = 0; i < lopperPointContainer.getChildCount(); i++) {
            View point = lopperPointContainer.getChildAt(i);
            //设置指示器背景shape
            if (i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_indecator_point);
            } else {
                point.setBackgroundResource(R.drawable.shape_indecator_point_normal);
            }
        }
    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> contents) {
        //数据列表加载加载到了
        contentAdapter.loadData(contents);
        setState(State.SUCCESS);

    }

    @Override
    public void onLoading() {
        //加载中
        setState(State.LOADING);
    }

    @Override
    public int getCategoryId() {
        return materialId;
    }

    @Override
    public void onNatworkError() {
        //网络错误
        setState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        //内容为空
        setState(State.EMPTY);
    }

    @Override
    public void onLoadMoreErroor() {
        //加载更多出现错误
        TostUtils.showToast("网络异常，请检查后重试");
        //结束加载更多动画
        if (refreshLayout != null) {
            refreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLoadMoreEmptyt() {
        //无更多内容
        TostUtils.showToast("没有更多内容了");
        //结束加载更多动画
        if (refreshLayout != null) {
            refreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLoadMoreLoaded(List<HomePagerContent.DataBean> contents) {
        //加载更多
        contentAdapter.addData(contents);
        //结束加载更多动画
        if (refreshLayout != null) {
            refreshLayout.finishLoadmore();
        }
        TostUtils.showToast("加载了" + contents.size() + "件商品");
    }

    @Override
    public void onLooperListLoaded(List<HomePagerContent.DataBean> contents) {
        //加载轮播图
//        Log.d(String.valueOf(HomePagerFragment.class), "contents----->" + contents.size());
        looperPagerAdapter.setData(contents);
        //因为中间点%数据的size不一定为0，所以显示的不是第一个，处理方法
        int dx = (Integer.MAX_VALUE / 2) % contents.size();
        int targetCententsPosition = (Integer.MAX_VALUE / 2) - dx;
        //设置中间点
        looperPager.setCurrentItem(targetCententsPosition);
        //设置圆点指示器
        lopperPointContainer.removeAllViews();
        for (int i = 0; i < contents.size(); i++) {
            View point = new View(getContext());
            int i1 = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(i1, i1);
            layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
            layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);
            point.setLayoutParams(layoutParams);
            if (i == 0) {
                point.setBackgroundResource(R.drawable.shape_indecator_point);
            } else {
                point.setBackgroundResource(R.drawable.shape_indecator_point_normal);
            }
            lopperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if (categoryPagerPresenter != null) {
            categoryPagerPresenter.unregisiterViewCallback(this);
        }
    }

    @Override
    public void onItemClick(IBsaeInfo item) {
        //列表内容
        handleItemClick(item);
    }



    @Override
    public void onLoopItemClick(IBsaeInfo item) {
        //轮播图内容
        handleItemClick(item);
    }

    private void handleItemClick(IBsaeInfo item) {

//        String title = item.getTitle();
//        //有券领券
//        String url = item.getCoupon_click_url();
//        if (url.isEmpty()){
//            //无券进商品详情
//            url = item.getClick_url();
//        }
//        String cover = item.getPict_url();
//        ticketPresenter = PresenterManager.getInstance().getTicketPresenter();
//        ticketPresenter.getTicket(title,url,cover);
//        goTo(TicketActivity.class);

        TicketUtil.toTicketPage(getContext(),item);
    }
}
